package com.cn.kehong.service;


import com.alibaba.fastjson.JSONObject;
import com.cn.kehong.api.IPhysicalChemicalService;
import com.cn.kehong.api.IProductPackageService;
import com.cn.kehong.conf.Config;
import com.cn.kehong.dao.*;
import com.cn.kehong.domain.*;
import com.cn.kehong.utils.*;
import com.google.common.collect.Lists;

import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.TimeUnit;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

@Service
public class PhysicalChemicalServiceImpl implements IPhysicalChemicalService {

    @Autowired
    private PhysicalChemicalMapper physicalChemicalMapper;

    @Autowired
    private IProductPackageService productPackageService;

    @Autowired
    private GenerateUUID generateUUID;

    @Autowired
    private Config config;

    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private LineTaskMapper lineTaskMapper;

    @Autowired
    private LoginMapper loginMapper;

    @Autowired
    private FactoryShiftMapper factoryShiftMapper;
    @Override
    public List<PhysicalChemicalVo> getPhysicalChemicalsList(QueryForm queryForm) throws Exception {
        if (queryForm.getStatus().equals("1")){
            int count = physicalChemicalMapper.getPhysicalChemicalsCheckCount(queryForm);
            if (count == 0) {
                return Lists.newArrayList();
            }
            List<PhysicalChemicalVo> physicalChemicals = physicalChemicalMapper.getPhysicalChemicalsCheckList(queryForm);
            physicalChemicals.get(0).setCount(count);
            return  physicalChemicals;
        }
        int count = physicalChemicalMapper.getPhysicalChemicalsCount(queryForm);
        if (count == 0) {
            return Lists.newArrayList();
        }
        List<PhysicalChemicalVo> physicalChemicals = physicalChemicalMapper.getPhysicalChemicalsList(queryForm);

        physicalChemicals.get(0).setCount(count);
        return  physicalChemicals;
    }

    @Override
    public String cancle(QueryForm queryForm) {
        String id = queryForm.getId();
        String updateBy=queryForm.getUpdateBy();
        PhysicalChemical chemical = new PhysicalChemical();
        chemical.setStatus("2");
        chemical.setUpdateBy(updateBy);
        PhysicalChemicalExample example = new PhysicalChemicalExample();
        example.createCriteria().andIdEqualTo(id);
        int count = physicalChemicalMapper.updateByExampleSelective(chemical,example);
        if (count < 1) {
            return  "取消失败！";
        }
        return CommonUtil.outStr(count);
    }

    @Override
    public List<PhysicalChemicalVo> getPhysicalGranularity(QueryForm queryForm) throws Exception {

        if (queryForm.getStatus().equals("1")){
            int count = physicalChemicalMapper.getPhysicalGranularityCheckCount(queryForm);
            if (count == 0) {
                return Lists.newArrayList();
            }
            List<PhysicalChemicalVo> physicalChemicals = physicalChemicalMapper.getPhysicalGranularityCheckList(queryForm);
            physicalChemicals.get(0).setCount(count);
            return  physicalChemicals;
        }
        int count = physicalChemicalMapper.getPhysicalGranularityCount(queryForm);
        if (count == 0) {
            return Lists.newArrayList();
        }
        List<PhysicalChemicalVo> physicalChemicals = physicalChemicalMapper.getPhysicalGranularity(queryForm);
        physicalChemicals.get(0).setCount(count);

        physicalChemicals.get(0).setCount(count);
        return  physicalChemicals;
    }

    @Override
    public List<PhysicalChemicalVo> getPhysicalChemicalCount(QueryForm queryForm) throws Exception {
        int count = physicalChemicalMapper.getPhysicalChemicalWaterCount(queryForm);
        if (count == 0) {
            return Lists.newArrayList();
        }
        ArrayList<PhysicalChemicalVo> physicalChemicals = new ArrayList<>();
        PhysicalChemicalVo physicalChemicalVo = new PhysicalChemicalVo();
        physicalChemicalVo.setCount(count);
        physicalChemicals.add(physicalChemicalVo);
        return  physicalChemicals;
    }

    @Override
    public List<PhysicalChemicalVo> getGranularityHaving(QueryForm queryForm) throws Exception {
        int count = physicalChemicalMapper.getGranularityHavingCount(queryForm.getTestNumber());
        if (count == 0) {
            return Lists.newArrayList();
        }
        List<PhysicalChemicalVo> physicalChemicals = physicalChemicalMapper.getGranularityHavingList(queryForm.getTestNumber());
        physicalChemicals.get(0).setCount(count);
        return  physicalChemicals;
    }

    @Override
    public List<PhysicalChemicalVo> getGranularityCount(QueryForm queryForm) throws Exception {
        int count = physicalChemicalMapper.getGranularityCount(queryForm);
        if (count == 0) {
            return Lists.newArrayList();
        }
        ArrayList<PhysicalChemicalVo> physicalChemicals = new ArrayList<>();
        PhysicalChemicalVo physicalChemicalVo = new PhysicalChemicalVo();
        physicalChemicalVo.setCount(count); // 设置计数
        physicalChemicals.add(physicalChemicalVo); // 将实例添加到列表中
        return  physicalChemicals;
    }

    @Override
    public List<PhysicalChemicalVo> getWaterHaving(QueryForm queryForm) throws Exception {
        int count = physicalChemicalMapper.getWaterHavingCount(queryForm.getTestNumber());
        if (count == 0) {
            return Lists.newArrayList();
        }
        List<PhysicalChemicalVo> physicalChemicals = physicalChemicalMapper.getWaterHavingList(queryForm.getTestNumber());
        physicalChemicals.get(0).setCount(count);
        return  physicalChemicals;
    }

    @Override
    public String addPhysicalChemical(PhysicalChemical physicalChemical) throws Exception {
        String relateId = physicalChemical.getRelateId();
        if(StringUtils.isEmpty(relateId)){
            return "relateId is null";
        }
        PhysicalChemicalExample example = new PhysicalChemicalExample();
        example.createCriteria().andRelateIdEqualTo(relateId).andStatusEqualTo(Constants.NORMAL_STATUS);
        int existCount = physicalChemicalMapper.countByExample(example);
        if(existCount > 0){
            return "送检记录已经存在";
        }
        String yearMoth = generateUUID.getYearMoth();
        String key = "phy"+yearMoth;
        int num = generateUUID.getNumberFlag(key);
        LocalDateTime now = LocalDateTime.now();
        String year = now.format(DateTimeFormatter.ofPattern("yyyy"));
        String year1 = year.substring(year.length() - 2);
        String month = now.format(DateTimeFormatter.ofPattern("MM"));
        String sampleCode ="T"+year1+month+ generateUUID.getFourNumStr(num);
        physicalChemical.setTestNumber(sampleCode);
        physicalChemical.setCreateTime(new Date());
        physicalChemical.setIsDel("0");
        physicalChemical.setStatus("0");
        physicalChemical.setItemType("1");
        physicalChemical.setSourceType("PC");
        String id = CommonUtil.generateRandomNum("physical-");
        physicalChemical.setId(id);
        int count = physicalChemicalMapper.insertSelective(physicalChemical);
        if(count < 1){
            return "插入数据异常";
        }
        String resp = productPackageService.updatePackageJobCheckCode(relateId,sampleCode);
        if(StringUtils.isNotEmpty(resp)){
            throw new Exception(resp);
        }
        return CommonUtil.outStr(count);
    }

    @Override
    public List<PhysicalChemical> getPhysicalChemicalByRelateId(String relateId) throws Exception {
        if(StringUtils.isEmpty(relateId)){
            return Lists.newArrayList();
        }
        PhysicalChemicalExample example = new PhysicalChemicalExample();
        example.createCriteria().andRelateIdEqualTo(relateId).andStatusEqualTo(Constants.NORMAL_STATUS);
        List<PhysicalChemical> physicalChemicals = physicalChemicalMapper.selectByExample(example);
        return physicalChemicals;
    }

    @Override
    public Map<String, Object> getLineInspectionByApp(QueryForm queryForm) throws Exception {
        Map<String, Object> resultMap = new HashMap<>();
        String factoryName = queryForm.getFactoryName();
        // 生产的送检记录
        if (queryForm.getSubmissionType().equals("0")) {
            PhysicalChemicalExample physicalChemicalExample = new PhysicalChemicalExample();
            physicalChemicalExample.createCriteria().andSubmissionTypeEqualTo("0").andTestTypeEqualTo("来料").andSourceTypeEqualTo("App").andFactoryWorkshopEqualTo(factoryName);
            List<PhysicalChemical> comingMaterial = physicalChemicalMapper.selectByExample(physicalChemicalExample);
            //来料
            if (comingMaterial.size() > 0) {
                comingMaterial.get(0).setCount(comingMaterial.size());
                resultMap.put("comingMaterial", comingMaterial);
            } else {
                resultMap.put("comingMaterial", new ArrayList<>());
            }
            // 过程
            PhysicalChemicalExample physicalChemicalExampleGc = new PhysicalChemicalExample();
            physicalChemicalExampleGc.createCriteria().andSubmissionTypeEqualTo("0").andTestTypeEqualTo("过程").andSourceTypeEqualTo("App").andFactoryWorkshopEqualTo(factoryName);
            List<PhysicalChemical> processMaterial = physicalChemicalMapper.selectByExample(physicalChemicalExampleGc);
            if (processMaterial.size() > 0) {
                processMaterial.get(0).setCount(processMaterial.size());
                resultMap.put("processMaterial", processMaterial);
            } else {
                resultMap.put("processMaterial", new ArrayList<>());
            }
            // 成品
            PhysicalChemicalExample physicalChemicalExampleCp = new PhysicalChemicalExample();
            physicalChemicalExampleCp.createCriteria().andSubmissionTypeEqualTo("0").andTestTypeEqualTo("成品").andSourceTypeEqualTo("App").andFactoryWorkshopEqualTo(factoryName);
            List<PhysicalChemical> finishedPoduct = physicalChemicalMapper.selectByExample(physicalChemicalExampleCp);
            if (finishedPoduct.size() > 0) {
                finishedPoduct.get(0).setCount(finishedPoduct.size());
                resultMap.put("finishedPoduct", finishedPoduct);
            } else {
                resultMap.put("finishedPoduct", new ArrayList<>());
            }
            //品质的送检记录
        }else if(queryForm.getSubmissionType().equals("1")){
            PhysicalChemicalExample physicalChemicalExample = new PhysicalChemicalExample();
            physicalChemicalExample.createCriteria().andSubmissionTypeEqualTo("1").andTestTypeEqualTo("来料").andSourceTypeEqualTo("App").andFactoryWorkshopEqualTo(factoryName);
            List<PhysicalChemical> comingMaterial = physicalChemicalMapper.selectByExample(physicalChemicalExample);
            //来料
            if (comingMaterial.size() > 0) {
                comingMaterial.get(0).setCount(comingMaterial.size());
                resultMap.put("comingMaterial", comingMaterial);
            } else {
                resultMap.put("comingMaterial", new ArrayList<>());
            }
            // 过程
            PhysicalChemicalExample physicalChemicalExampleGc = new PhysicalChemicalExample();
            physicalChemicalExampleGc.createCriteria().andSubmissionTypeEqualTo("1").andTestTypeEqualTo("过程").andSourceTypeEqualTo("App").andFactoryWorkshopEqualTo(factoryName);
            List<PhysicalChemical> processMaterial = physicalChemicalMapper.selectByExample(physicalChemicalExampleGc);
            if (processMaterial.size() > 0) {
                processMaterial.get(0).setCount(processMaterial.size());
                resultMap.put("processMaterial", processMaterial);
            } else {
                resultMap.put("processMaterial", new ArrayList<>());
            }
            // 成品
            PhysicalChemicalExample physicalChemicalExampleCp = new PhysicalChemicalExample();
            physicalChemicalExampleCp.createCriteria().andSubmissionTypeEqualTo("1").andTestTypeEqualTo("成品").andSourceTypeEqualTo("App").andFactoryWorkshopEqualTo(factoryName);
            List<PhysicalChemical> finishedPoduct = physicalChemicalMapper.selectByExample(physicalChemicalExampleCp);
            if (finishedPoduct.size() > 0) {
                finishedPoduct.get(0).setCount(finishedPoduct.size());
                resultMap.put("finishedPoduct", finishedPoduct);
            } else {
                resultMap.put("finishedPoduct", new ArrayList<>());
            }
        }
        return resultMap;
    }

    @Override
    public String addPhysicalChemicalByApp(PhysicalChemical physicalChemical) throws Exception {
        if (null == physicalChemical) {
            return "请输入送检任务";
        }
        if (physicalChemical.getTestType().equals("过程")){
            LocalDate currentDate = LocalDate.now();
            int year = currentDate.getYear();
            String yearStr = Integer.toString(year);
            String years = yearStr.substring(yearStr.length() - 2);
            String factoryName = physicalChemical.getFactoryWorkshop().split("-")[0];
            String productCode = factoryName + years + physicalChemical.getBatchNumber();
            physicalChemical.setBatchNumber(productCode);
        }
        String id = CommonUtil.generateRandomNum("physicalChemical_");
        physicalChemical.setId(id);
        //待检
        String yearMoth = generateUUID.getYearMoth();
        String key = "phy"+yearMoth;
        int num = generateUUID.getNumberFlag(key);
        LocalDateTime now = LocalDateTime.now();
        String year = now.format(DateTimeFormatter.ofPattern("yyyy"));
        String year1 = year.substring(year.length() - 2);
        String month = now.format(DateTimeFormatter.ofPattern("MM"));
        String sampleCode ="T"+year1+month+ generateUUID.getFourNumStr(num);
        physicalChemical.setStatus("0");
        physicalChemical.setTestNumber(sampleCode);
        physicalChemical.setIsDel("0");
        physicalChemical.setSourceType("App");
        physicalChemical.setCreateTime(new Date());
        int count = physicalChemicalMapper.insertSelective(physicalChemical);

        if (count < 1) {
            return "新增失败！";
        }
//        else {
//            printSampleInfo(physicalChemical.getId());
//        }
        return CommonUtil.outStr(count);
    }

    @Override
    public String printSampleInfo(String id) throws Exception {
        if(StringUtils.isEmpty(id)){
            return "id 不能为空";
        }
        PhysicalChemical physicalChemical = physicalChemicalMapper.selectByPrimaryKey(id);
        if(null == physicalChemical){
            return "未查询到送检信息！";
        }
        String factoryName = physicalChemical.getFactoryWorkshop();
        if(StringUtils.isEmpty(factoryName)){
            return "未查询到车间";
        }

        String ip =  "";
        if(StringUtils.equals(factoryName,"16-1")){
            ip = config.printIp161;
        }else if(StringUtils.equals(factoryName,"16-2")){
            ip = config.printIp162;
        }
        if(StringUtils.isEmpty(ip)){
            return "未查询到打印机";
        }
        JSONObject jsonObject = new JSONObject();

        String type = "";
        String testType = physicalChemical.getTestType();
        if(StringUtils.equals("成品",testType)){
            type = "1";
            String batchNum = physicalChemical.getBatchNumber();
            if(batchNum.indexOf("-") < 0){
                return "打印【成品批次包号】"+batchNum+"格式存在问题";
            }
            jsonObject.put("batchNum",batchNum.split("-")[0]);
            jsonObject.put("batchCode",batchNum.split("-")[1]);

        }else if(StringUtils.equals("来料",testType)){
            type = "3";
            jsonObject.put("supplier",physicalChemical.getSupplierName());
            jsonObject.put("gradeValue",physicalChemical.getSpecificationsType());
            jsonObject.put("batchNum",physicalChemical.getBatchNumber());
        }else if(StringUtils.equals("过程",testType)){
            type = "4";
            jsonObject.put("gradeValue",physicalChemical.getSpecificationsType());
            jsonObject.put("batchNum",physicalChemical.getBatchNumber());
        }
        jsonObject.put("type",type);
        jsonObject.put("factoryName",factoryName);
        jsonObject.put("sampleName",physicalChemical.getSampleName());
        jsonObject.put("itemName",physicalChemical.getInspectionItems());
        jsonObject.put("time",physicalChemical.getCreateTimeFt());
        jsonObject.put("sampleCode",physicalChemical.getTestNumber());
        System.out.println("===================jsonObject================"+jsonObject.toJSONString());
        redisTemplate.opsForList().leftPush(ip, jsonObject.toJSONString());
        redisTemplate.expire(ip, 60, TimeUnit.SECONDS);
        return null;
    }

    @Override
    public List<PhysicalChemicalVo> getPhysicalChemicalDetailByApp(QueryForm queryForm) throws Exception {
        //水分
        if (queryForm.getType().equals("0")){
            //待检
            if(queryForm.getStatus().equals("0")){
                List<PhysicalChemicalVo> physicalChemicalsByWaterDj = physicalChemicalMapper.getPhysicalChemicalDetailByWaterDj(queryForm,queryForm.getId());
                return  physicalChemicalsByWaterDj;
                //已检
            }else if(queryForm.getStatus().equals("1")){
                List<PhysicalChemicalVo> physicalChemicalsByWater = physicalChemicalMapper.getPhysicalChemicalDetailByWater(queryForm,queryForm.getId());
                return  physicalChemicalsByWater;
            }else if (queryForm.getStatus().equals("2")){
                //已取消
                List<PhysicalChemicalVo> physicalChemicalsByWaterDj = physicalChemicalMapper.getPhysicalChemicalDetailByWaterDj(queryForm,queryForm.getId());
                return  physicalChemicalsByWaterDj;
            }

        }else if (queryForm.getType().equals("1")){
            //待检
            if(queryForm.getStatus().equals("0")){
                List<PhysicalChemicalVo> physicalChemicalsByLdDj = physicalChemicalMapper.getPhysicalChemicalDetailByAppLdDj(queryForm,queryForm.getId());
                return  physicalChemicalsByLdDj;
                //已检
            }else if(queryForm.getStatus().equals("1")){
                List<PhysicalChemicalVo> physicalChemicalsByLd = physicalChemicalMapper.getPhysicalChemicalDetailByAppLd(queryForm,queryForm.getId());
                return  physicalChemicalsByLd;
            }else if (queryForm.getStatus().equals("2")){
                //已取消
                List<PhysicalChemicalVo> physicalChemicalsByLd = physicalChemicalMapper.getPhysicalChemicalDetailByAppLdDj(queryForm,queryForm.getId());
                return  physicalChemicalsByLd;
            }


        }
        return new ArrayList<>();
    }

    @Override
    public String redriving(PhysicalChemical physicalChemical) throws Exception {
        printSampleInfo(physicalChemical.getId());
        return null;
    }

    @Override
    public Map<String, Object> getOtherToday() throws Exception {
        LocalDateTime startDateTime = LocalDateTime.now().withHour(0).withMinute(0).withSecond(0);
        LocalDateTime endDateTime = LocalDateTime.now().withHour(23).withMinute(59).withSecond(59);
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String startTime = startDateTime.format(formatter);
        String endTime = endDateTime.format(formatter);



        Map<String, Object> resultMap = new HashMap<>();
        QueryForm queryForm = new QueryForm();
        Map<String,String> dutyMap = CommonUtil.getOnDutyAndWhiteDay();

        //本班出勤
        FactoryShiftExample example1 = new FactoryShiftExample();
        example1.createCriteria().andShiftTypeEqualTo(dutyMap.get("whiteDay"));
        List<FactoryShift> factoryShifts = factoryShiftMapper.selectByExample(example1);
        int shiftUserCount=0;
        for (FactoryShift factoryShift:factoryShifts){
            shiftUserCount += Integer.valueOf(factoryShift.getShiftUserCount());
        }
        resultMap.put("shiftUserCount",shiftUserCount);

        //水分待检
        queryForm.setStatus("0");
        int sfCount = physicalChemicalMapper.getPhysicalChemicalsCheckCount(queryForm);
        resultMap.put("sfCount",sfCount);

        //粒度待检
        queryForm.setStatus("0");
        int ldCount = physicalChemicalMapper.getPhysicalGranularityCheckCount(queryForm);
        resultMap.put("ldCount",ldCount);

        //包装机维保
        queryForm.setStatus("0");
        queryForm.setTaskName("包装机维保");
        queryForm.setStartTime(startTime);
        queryForm.setEndTime(endTime);
        int bzj=lineTaskMapper.getcountByToday(queryForm);
        resultMap.put("bzj",bzj);

        //系统用户数量
        LoginExample example = new LoginExample();
        example.createCriteria().andStatusEqualTo(Constants.NORMAL_STATUS);
        int xtCount = loginMapper.countByExample(example);
        resultMap.put("xtCount",xtCount);
        return resultMap;
    }

}
